package com.netinfo.springboot.service.impl;

import com.github.pagehelper.PageHelper;
import com.netinfo.springboot.common.ServerResponse;
import com.netinfo.springboot.entity.Car;
import com.netinfo.springboot.enums.ResultEnum;
import com.netinfo.springboot.exception.MyException;
import com.netinfo.springboot.mapper.CarMapper;
import com.netinfo.springboot.service.CarService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CarServiceImpl implements CarService {

    @Autowired
    private CarMapper carMapper;

    @Override
    public ServerResponse getCarList(Integer pageNum,Integer pageSize) {
        //开始分页
        PageHelper.startPage(pageNum,pageSize);
        List<Car> carList = null;
        try {
            carList = carMapper.selectAll();
        } catch (Exception e) {
            throw new RuntimeException(ResultEnum.QUERY_ERROR.getMessage());
        }
        return ServerResponse.createBySuccess(ResultEnum.QUERY_SUCCESS.getMessage(),carList);
    }

    @Override
    public ServerResponse<Car> getCarById(Integer id) {
        Car car = null;
        try {
            car = carMapper.selectByPrimaryKey(id);

        }catch (Exception e){
            throw new RuntimeException(ResultEnum.QUERY_ERROR.getMessage());
        }
        return ServerResponse.createBySuccess(ResultEnum.QUERY_SUCCESS.getMessage(),car);
    }

    @Override
    public ServerResponse addCar(Car car) {
        int result = carMapper.insert(car);
        if (result>0){
            return ServerResponse.createBySuccessMessage(ResultEnum.ADD_SUCCESS.getMessage());
        }
        return ServerResponse.createByErrorMessage(ResultEnum.ADD_FILED.getMessage());
    }

    @Override
    public ServerResponse delCar(Integer id) {

        try {
            int result = carMapper.deleteByPrimaryKey(id);
        } catch (Exception e) {
            throw new MyException(ResultEnum.ERROR);
        }
        return ServerResponse.createBySuccessMessage(ResultEnum.SUCESS.getMessage());
    }

    @Override
    public ServerResponse updateCar(Car car) {
        try {
            int i = carMapper.updateByPrimaryKeySelective(car);
        } catch (Exception e) {
            throw new RuntimeException(ResultEnum.ERROR.getMessage());
        }
        return ServerResponse.createBySuccessMessage(ResultEnum.SUCESS.getMessage());
    }
}
